package com.dahuyou.link.monitoring;

import net.bytebuddy.asm.Advice;
import java.util.UUID;

public class MyByteBuddyAdvice {
    @Advice.OnMethodEnter()
    public static void enter(@Advice.Origin("#t") String className, @Advice.Origin("#m") String methodName) {
        String traceId = TrackManager.getCurrentTraceId();
        // a->b->c 当方法a执行时是没有traceId的，则创建并设置
        if (null == traceId) {
            traceId = UUID.randomUUID().toString();
            TrackContext.setTraceId(traceId);
        }
        // 记录该次方法调用对应的span，调用了几个方最终就生成几个span
        Span entrySpan = TrackManager.createEntrySpan(className, methodName);
        System.out.println("链路追踪：" + entrySpan.getTraceId() + ", 类： " + className + ", 方法：" + methodName + ", 线程：" + Thread.currentThread().getName());
    }

    /**
     * 方法栈帧从方法栈弹出时执行（方法执行结束）
     * @param className
     * @param methodName
     */
    @Advice.OnMethodExit()
    public static void exit(@Advice.Origin("#t") String className, @Advice.Origin("#m") String methodName) {
        System.out.println("--------------");
        TrackManager.getAllSpan();
    }

}
